package io.zhiller.ollamaclient.screen.drawer

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.DrawerState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import io.zhiller.ollamaclient.R
import io.zhiller.ollamaclient.api.git.GitService
import io.zhiller.ollamaclient.di.viewmodel.AppVM
import io.zhiller.ollamaclient.ui.navigation.NavActions
import io.zhiller.ollamaclient.ui.navigation.SinglePageRoutes
import io.zhiller.ollamaclient.utils.LoggerUtils
import io.zhiller.ollamaclient.utils.ScreenUtils
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.compose.koinInject

@Composable
fun ScaffoldDrawerContent(navController: NavController, drawerState: DrawerState) {
  val context = LocalContext.current
  val drawerWidth = ScreenUtils.getScreenWidthDp(context).times(0.7f)
  val scope = rememberCoroutineScope()
  
  val gitService = koinInject<GitService>()
  val appVm = koinViewModel<AppVM>()
  val isConnected = appVm.state.collectAsState().value.apiUrl
  
  Surface(
    modifier = Modifier
      .fillMaxHeight()
      .width(drawerWidth)
      .clip(RoundedCornerShape(12.dp)),
  ) {
    Column(
      modifier = Modifier.windowInsetsPadding(WindowInsets.navigationBars),
      verticalArrangement = Arrangement.SpaceBetween
    ) {
      Column(
        modifier = Modifier
          .fillMaxWidth()
          .weight(1f)
          .verticalScroll(rememberScrollState())
      ) {
        Surface(modifier = Modifier
          .fillMaxWidth()
          .clickable {
            when {
              drawerState.isClosed -> {
                scope.launch {
                  drawerState.open()
                }
              }
              
              else -> {
                scope.launch {
                  drawerState.close()
                }
              }
            }
          }) {
          Column(
            modifier = Modifier
              .padding(horizontal = 16.dp, vertical = 18.dp)
              .windowInsetsPadding(WindowInsets.statusBars)
          ) {
            Text(
              stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge.copy(
                fontWeight = FontWeight.Bold,
              )
            )
          }
        }
      }
      
      DrawerBottomToolBar(navController)
    }
  }
}

@Composable
fun DrawerBottomToolBar(navController: NavController) {
  val gitService = koinInject<GitService>()
  val appVm = koinViewModel<AppVM>()
  val isConnected = appVm.state.collectAsState().value.apiUrl
  
  Column(
    modifier = Modifier.fillMaxWidth()
  ) {
    HorizontalDivider()
    Row(
      modifier = Modifier
        .padding(horizontal = 16.dp)
        .fillMaxWidth()
        .clickable {
          if (isConnected.isEmpty()) {
            gitService.getApiUrl(onSuccess = {
              LoggerUtils.debug("GitService: ON_SUCCESS")
              LoggerUtils.info("GitService: ON_SUCCESS: ${it.data}")
              appVm.updateApiUrl(it.data?.content ?: "")
            }, onError = {
              LoggerUtils.error(it.toString())
            })
          }
        },
      verticalAlignment = Alignment.CenterVertically,
      horizontalArrangement = Arrangement.SpaceBetween
    ) {
      Text(
        text = if (isConnected.isNotEmpty()) "已连接服务器" else "链接服务器失败(点击重试)",
        style = MaterialTheme.typography.titleSmall
      )
      
      IconButton(onClick = {
        NavActions(navController).navToPage(SinglePageRoutes.Setting.route)
      }) {
        Icon(
          imageVector = Icons.Default.Settings,
          contentDescription = null,
        )
      }
    }
  }
}

//@Composable
//fun DrawerNavItemGroup(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
//  Box(
//    modifier = modifier
//      .fillMaxWidth()
//  ) {
//    content()
//  }
//}
//
//@Composable
//fun DrawerNavItemComp(
//  modifier: Modifier = Modifier,
//  icon: ImageVector,
//  title: String,
//  onClick: () -> Unit
//) {
//  Box(
//    modifier = modifier
//      .fillMaxWidth()
//      .clickable {
//        onClick()
//      }
//  ) {
//    Row(
//      modifier = Modifier
//        .fillMaxWidth()
//        .padding(12.dp),
//      verticalAlignment = Alignment.CenterVertically,
//      horizontalArrangement = Arrangement.spacedBy(8.dp)
//    ) {
//      Icon(
//        imageVector = icon,
//        contentDescription = null,
//        modifier = Modifier.size(16.dp)
//      )
//      Text(
//        text = title,
//        style = MaterialTheme.typography.titleSmall
//      )
//    }
//  }
//}